package com.epc.easypurchase.fragment

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.webkit.*
import com.epc.easypurchase.R
import com.epc.easypurchase.activity.LoginActivity
import com.epc.easypurchase.activity.MainActivity
import com.epc.easypurchase.mvp.contract.LogoutContract
import com.epc.easypurchase.mvp.presenter.LogoutPresenter
import com.epc.easypurchase.util.SimpleDialogUtil
import com.epc.easypurchase.activity.web.CommonWebViewActivity
import com.epc.easypurchase.constant.SPUserConstants
import com.epc.easypurchase.util.SPUserUtil
import com.jiazhuo.blockgamesquare.util.toast
import com.skateboard.zxinglib.CaptureActivity
import com.woochen.baselibrary.base.mvp.BaseMvpFragment
import com.woochen.baselibrary.mvp.InjectPresenter
import kotlinx.android.synthetic.main.activity_common_web_view.*
import com.tbruyelle.rxpermissions2.RxPermissions


/**
 * Created by chenwuchao on 2018/11/24.
 */
class TestFragment : BaseMvpFragment(), LogoutContract.ILogoutView {

    @InjectPresenter
    lateinit var mLogoutPresenter: LogoutPresenter

    private val SCAN_REQUEST_CODE = 0x0010
    private val LOGIN_REQUEST_CODE = 0x0011


    override fun logoutSucess() {
        startActivity(MainActivity::class.java)
    }

    override fun setContentView(): Int = R.layout.frament_main

    companion object {
        private val URL_NAME: String = "url_name"

        fun newInstance(url: String): TestFragment {
            val homeFragment = TestFragment()
            val arguments = Bundle()
            arguments.putString(URL_NAME, url)
            homeFragment.arguments = arguments
            return homeFragment
        }
    }


    override fun initView() {
        rxPermissions = RxPermissions(this)
        initWebView()
        val url = this.arguments.getString(URL_NAME)
//        web.loadUrl(url)
        val headParams = hashMapOf<String, String>()
        val token = SPUserUtil.getString(SPUserConstants.USER_TOKEN)!!
        headParams.put("epc-token",token )
        web.loadUrl("file:///android_asset/index.html",headParams);
    }


    private fun initWebView() {
        web.webViewClient = object : WebViewClient() {

            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                showContent()
            }


        }
        val webSettings = web.settings
        webSettings.javaScriptEnabled = true
        webSettings.javaScriptCanOpenWindowsAutomatically = true
        web.addJavascriptInterface(this, "android")
        // 支持缩放(适配到当前屏幕)
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {//少于4.4（不包括4.4）用这个
            webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        }
        //适应屏幕，大于等于4.4用这个
        webSettings.useWideViewPort = true
        webSettings.setSupportZoom(true)
        webSettings.loadWithOverviewMode = true
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE//不缓存

        web.webChromeClient = object: WebChromeClient() {
            override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
                Log.e("tag", ": " + message );
                return super.onJsAlert(view, url, message, result)
            }
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        println("TestFragment->" + requestCode)
        if (requestCode == SCAN_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            val result = data?.getStringExtra(CaptureActivity.KEY_DATA)
            toast("qrcode result is $result")
        }else if (requestCode == LOGIN_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
             (mContext as Activity).finish()
        }
    }


    @JavascriptInterface
    fun logout() {
        activity.runOnUiThread {
            SimpleDialogUtil.confirmAndCancel(mContext, R.string.tip_logout, R.string.cancle, R.string.confirm,
                    object : SimpleDialogUtil.SimpleClickListener {
                        override fun confirm() {
                            mLogoutPresenter.logout()
                        }

                    })
        }

    }

    @JavascriptInterface
    fun openNewPage(url: String) {
        CommonWebViewActivity.start(mContext, url)
    }


    /**
     * 扫一扫
     */
    @JavascriptInterface
    fun scanCode() {
        activity.runOnUiThread {
            rxPermissions
                    .request(Manifest.permission.CAMERA)
                    .subscribe({ granted ->
                        if (granted) {
                            println("已授权")
                            val intent = Intent(mContext, CaptureActivity::class.java)
                            startActivityForResult(intent, SCAN_REQUEST_CODE)
                        } else {
                            println("缺少相机权限！")
                            toast("缺少相机权限！")
                        }
                    })

        }

    }

    private lateinit var rxPermissions: RxPermissions

    /**
     * 预览pdf
     */
    @JavascriptInterface
    fun previewPdf(pdfUrl: String) {
        val prePdfDialog = PrePdfDialog.newInsatance(pdfUrl)
        prePdfDialog.show(fragmentManager, "prePdf")

    }

    @JavascriptInterface
    fun login(){
        startActivity(LoginActivity::class.java)
    }


}